import React, {PureComponent} from 'react';
import {View, ScrollView, Text, Button, Image, StyleSheet} from 'react-native';
import {connect} from 'react-redux';

import {actionChangeNum, actionGetBanners} from '../../store/homeStore/action';

class Home extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      name: '',
    };
  }
  componentDidMount() {
    this.props.getBanners();
  }
  // 设置缓存数据(userInfo)
  setStorageUserInfo() {
    global.storage.save({
      key: 'userInfo',
      data: {name: 'rocyuan'},
    });
  }
  // 获取缓存数据(userInfo)
  getStorageUserInfo() {
    global.storage
      .load({key: 'userInfo'})
      .then(userInfo => {
        this.setState({
          name: userInfo.name,
        });
      })
      .catch(() => {
        this.setState({
          name: '',
        });
      });
  }
  // 删除缓存中的数据(userInfo)
  removeStorageUserInfo() {
    global.storage.remove({key: 'userInfo'});
    this.getStorageUserInfo();
  }
  render() {
    return (
      <ScrollView>
        <Text style={styles.textCenter}>rocyuan666</Text>
        {/* redux 数据更改 */}
        <Text style={styles.textCenter}>{this.props.num}</Text>
        <Button
          title="+1"
          onPress={() => {
            this.props.changeNum(1);
          }}
        />
        <Button
          title="-1"
          onPress={() => {
            this.props.changeNum(-1);
          }}
        />
        {/* 存取删缓存数据 */}
        <Button
          title="缓存中储存userinfo"
          onPress={() => {
            this.setStorageUserInfo();
          }}
        />
        <Text style={styles.textCenter}>
          缓存中的userInfo.name：{this.state.name}
        </Text>
        <Button
          title="缓存中获取userinfo"
          onPress={() => {
            this.getStorageUserInfo();
          }}
        />
        <Button
          title="缓存中删除userinfo"
          onPress={() => {
            this.removeStorageUserInfo();
          }}
        />
        <View>
          {this.props.banners.map(item => {
            return (
              <View key={item.imageUrl}>
                <Image
                  source={{uri: item.imageUrl}}
                  // eslint-disable-next-line react-native/no-inline-styles
                  style={{width: '100%', height: 150}}
                />
              </View>
            );
          })}
        </View>
      </ScrollView>
    );
  }
}

const mapStateToProps = state => {
  return {
    num: state.home.num,
    banners: state.home.banners,
  };
};

const mapDispatchToProps = dispatch => {
  return {
    changeNum: num => {
      dispatch(actionChangeNum(num));
    },
    getBanners: () => {
      dispatch(actionGetBanners());
    },
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(Home);

// 样式
const styles = StyleSheet.create({
  textCenter: {
    textAlign: 'center',
  },
});
